package com.xszx.server.service;

import com.xszx.server.dto.Page;
import com.xszx.server.dto.RoleDto;
import com.xszx.server.entity.RoleResource;
import com.xszx.server.mapper.RoleResourceMapper;
import com.xszx.server.util.UuidUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleResourceService {
    @Resource
    private RoleResourceMapper roleResourceMapper;

    /**
     * 获取分页列表
     * @param page
     * @return
     */
    public Page getAllRoleResources(Page page){
        int pageNum = page.getPage();
        page.setPage((page.getPage()-1)*page.getSize());
        page.setList(roleResourceMapper.findAll(page));
        page.setTotal(roleResourceMapper.findCount());
        page.setPage(pageNum);
        return page;
    }

    /**
     * 新增或者删除信息
     * @param roleResource
     * @return
     */
    public String saveOrUpdate(RoleResource roleResource){
        if(StringUtils.isEmpty(roleResource.getId())){
            roleResource.setId(UuidUtil.getShortUuid());
            return (roleResourceMapper.insert(roleResource)>0)?"添加成功":"添加失败";
        }else{
            return (roleResourceMapper.updateByPrimaryKey(roleResource)>0)?"更新成功":"更新失败";
        }
    }

    /**
     * 物理删除角色资源关联
     * @param id
     * @return
     */
    public int del(String id){
        return roleResourceMapper.deleteByPrimaryKey(id);
    }

    /*
    保存数据
     */
    @Transactional
    public void saveResources(RoleDto roleDto){
       //角色的id
        String roleId = roleDto.getId();
        //资源的ids
        List<String> resourceIds = roleDto.getResourceIds();
        //删除当前角色的资源信息
        roleResourceMapper.deleteByRoleId(roleId);
        //循环添加
        for (String resourceId : resourceIds) {
            roleResourceMapper.insert(new RoleResource(UuidUtil.getShortUuid(),roleId,resourceId));
        }
    }
    public List<String> getResourcesByRoleId(String roleId){
        return roleResourceMapper.findResourcesByRoleId(roleId);
    }
     /**
     * 获取单个角色资源关联
     * @return
     */
    public RoleResource getRoleResource(String id){
        return roleResourceMapper.selectByPrimaryKey(id);
    }
}
